<?php
namespace app\api\middleware;

use app\common\model\StaffModel;
use app\common\model\UserModel;

class Check{
    public function handle($request, \Closure $next)
    {
        $code = $request->param('code/d',0);
        if(empty($code)){
            $miniapp_firm_id = $request->param('firm_id/d',0);
            if($miniapp_firm_id === 0){
                return error('非法访问#101'.$miniapp_firm_id);
            }
            // 没有员工code，随机获取一个
            $staff_info = StaffModel::where('firm_id',$miniapp_firm_id)->find();
        }else{
            $staff_info = StaffModel::where('code',$code)->find();
        }
        
        if(null === $staff_info){
            return error('员工不存在'.$code);
        }
        $request->staff_info = $staff_info;//员工详细信息
        $request->user_info = null;
        $open_id = $request->param('open_id/s','');
        if($open_id){
            if(null === $user_info = UserModel::where('open_id',$open_id)->find()){
                $user_info = new UserModel();
                $user_info->firm_id = $staff_info->firm_id;
                $user_info->open_id = $open_id;
                $user_info->save();
            }
            $request->user_info = $user_info;//用户详细信息
        }
        return $next($request);
    }
}